package com.siyuanren.gcocp.util;

/**
 * Created by   anxing
 * Project_name gcocp-parent
 * Path         com.siyuanren.gcocp.util
 * Date         2018/6/27
 * Time         10:56
 * Description
 */
import com.mysql.cj.protocol.WatchableOutputStream;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.builder.kefu.ImageBuilder;
import net.coobird.thumbnailator.Thumbnailator;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import sun.awt.SunHints;

import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.*;

import javax.imageio.ImageIO;
import javax.swing.*;
@Slf4j
public class NewImageUtil {
    /**
     *
     * @Title: 构造图片
     * @Description: 生成水印并返回java.awt.image.BufferedImage
     * @param srcImg
     *            源文件(图片)
     * @param waterImg
     *            水印文件(图片)
     * @param x
     *            距离右下角的X偏移量
     * @param y
     *            距离右下角的Y偏移量
     * @param alpha
     *            透明度, 选择值从0.0~1.0: 完全透明~完全不透明
     * @return BufferedImage
     * @throws IOException
     */
    public static BufferedImage watermark(BufferedImage srcImg, BufferedImage waterImg, int x, int y, float alpha) throws IOException {
       // 创建Graphics2D对象，用在底图对象上绘图
        Graphics2D g2d = srcImg.createGraphics();
        int waterImgWidth = waterImg.getWidth();// 获取层图的宽度
        int waterImgHeight = waterImg.getHeight();// 获取层图的高度
        // 在图形和图像中实现混合和透明效果
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
        // 绘制
        g2d.drawImage(waterImg, x, y, waterImgWidth, waterImgHeight, null);
        g2d.dispose();// 释放图形上下文使用的系统资源
        return srcImg;
    }

    /**
     * 输出水印图片
     *
     * @param buffImg
     *            图像加水印之后的BufferedImage对象
     * @param savePath
     *            图像加水印之后的保存路径
     */
    public static void generateFile(BufferedImage buffImg, String savePath) {
        int temp = savePath.lastIndexOf(".") + 1;
        try {
            ImageIO.write(buffImg, savePath.substring(temp), new File(savePath));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 增加文字水印
     * @param bufImg
     * @param word
     * @param x
     * @param y
     */
    public static void addWordMark(BufferedImage bufImg, String word, int x, int y) {
        log.info("water word: " + word);
        Color markContentColor = new Color(118, 98, 99);
//        Font font = new Font("PingFangSC-Bold", Font.BOLD, 34);
        Font font = new Font("LucidaTypewriterBold", Font.BOLD, 34);
        try {
            Graphics2D g = bufImg.createGraphics();
            g.setColor(markContentColor); //根据图片的背景设置水印颜色
            g.setFont(font);              //设置字体
            g.setRenderingHint(SunHints.KEY_ANTIALIASING, SunHints.VALUE_ANTIALIAS_OFF);
            g.setRenderingHint(SunHints.KEY_TEXT_ANTIALIASING, SunHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
            g.setRenderingHint(SunHints.KEY_STROKE_CONTROL, SunHints.VALUE_STROKE_DEFAULT);
            g.setRenderingHint(SunHints.KEY_TEXT_ANTIALIAS_LCD_CONTRAST, 140);
            g.setRenderingHint(SunHints.KEY_FRACTIONALMETRICS, SunHints.VALUE_FRACTIONALMETRICS_OFF);
            g.setRenderingHint(SunHints.KEY_RENDERING, SunHints.VALUE_RENDER_DEFAULT);
            //设置水印的坐标
            g.drawString(word, x, y);  //画出水印
            g.dispose();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    private static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }

    /**
     * 传入的图像必须是正方形的 才会 圆形 如果是长方形的比例则会变成椭圆的
     *
     * @param bi1
     *            用户头像地址
     * @return
     * @throws IOException
     */
    public static BufferedImage convertCircular(BufferedImage bi1) throws IOException {

        // 根据需要是否使用 BufferedImage.TYPE_INT_ARGB
        BufferedImage image = new BufferedImage(bi1.getWidth(), bi1.getHeight(),
                BufferedImage.TYPE_INT_ARGB);

        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1
                .getHeight());

        Graphics2D g2 = image.createGraphics();
        image = g2.getDeviceConfiguration().createCompatibleImage(bi1.getWidth(), bi1.getHeight(), Transparency.TRANSLUCENT);
        g2 = image.createGraphics();
        g2.setComposite(AlphaComposite.Clear);
        g2.fill(new Rectangle(image.getWidth(), image.getHeight()));
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
        g2.setClip(shape);
        // 使用 setRenderingHint 设置抗锯齿
        g2.drawImage(bi1, 0, 0, null);
        g2.dispose();
        return image;
    }


    static BufferedImage getBufferImage(File file) {
        ImageIcon src = new ImageIcon(file.getAbsolutePath());
        BufferedImage bufferedImage = new BufferedImage(src.getIconWidth(),
                src.getIconHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferedImage.createGraphics();
        g.setColor(Color.white);
        g.fillRect(0, 0, src.getIconWidth(), src.getIconHeight());
        g.drawImage(src.getImage(), 0, 0, null);
        g.dispose();
        return bufferedImage;
    }

    public static BufferedImage getActiveImage(File activeBg, File qrcodeFile, File userImage, String userName) {
        // 构建叠加层
        BufferedImage src = null;
        try {
            src = NewImageUtil.getBufferImage(activeBg);
            BufferedImage header = NewImageUtil.getBufferImage(userImage);
            BufferedImage qrcode = NewImageUtil.getBufferImage(qrcodeFile);
            NewImageUtil.addWordMark(src, userName, 210, 290);
            header = NewImageUtil.convertCircular(header);
            /* 新生成结果图片 */
            BufferedImage headerNew = new BufferedImage(80, 80, BufferedImage.TYPE_INT_ARGB);
            headerNew.getGraphics().drawImage( header.getScaledInstance(80, 80, Image.SCALE_SMOOTH), 0, 0, null);
            NewImageUtil.watermark(src, headerNew, 110, 250, 1.0f);
            NewImageUtil.watermark(src, qrcode, 103, 1000, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return src;
    }
    /**
     *
     * @param args
     * @throws IOException
     *             IO异常直接抛出了
     * @author bls
     */
    public static void main(String[] args) throws IOException {
        String sourceFilePath = "D://img//di.jpg";
        String headerFilePath = "D://img//header.jpg";
        String saveFilePath = "D://img//new.jpg";
        String qrcode = "D://img//qrcode.jpg";
        // 构建叠加层
//        BufferedImage src = NewImageUtil.getBufferImage(new File(sourceFilePath));
//        BufferedImage qrc = NewImageUtil.getBufferImage(new File(qrcode));
//        BufferedImage water = NewImageUtil.getBufferImage(new File(waterFilePath));
//        BufferedImage header = NewImageUtil.getBufferImage(new File(sourceFilePath));
//        NewImageUtil.watermark(src, water, 0, 0, 1.0f);
//
//        NewImageUtil.addWordMark(src, "戴依依", 220, 380);
//
//        header = NewImageUti.convertCircular(header);
//        Thumbnails.of(header).size(80, 80).toFile(headerNewPath);
//        BufferedImage headerNew = ImageIO.read(new File(headerNewPath));
//        NewImageUtil.watermark(src, headerNew, 120, 340, 1.0f);
//

//        BufferedImage activeImage = NewImageUtil.getActiveImage(new File(sourceFilePath),new File(qrcode), new File(headerFilePath), "戴依依");
//        NewImageUtil.generateFile(activeImage, saveFilePath);


        /* 新生成结果图片 */
        BufferedImage src = NewImageUtil.getBufferImage(new File(sourceFilePath));
        BufferedImage qrc = NewImageUtil.getBufferImage(new File(qrcode));
        NewImageUtil.watermark(src, qrc, 103, 1170, 1);
        NewImageUtil.generateFile(src, saveFilePath);

    }
}